//
//  ST_HotWaterfallViewController.swift
//  btvideo
//
//  Created by mac on 2020/4/23.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import SwiftyJSON
//import ST_CHTCollectionViewWaterfallLayout

/**
 时下最火特质 查看更多 暂时没用了
 */
class ST_HotWaterfallViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white

        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        view.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        
//        view.addSubview(right_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
        title_nav_btn.setTitleForAllStates("时下最火特质")

         
        
        view.insertSubview(collectionView, belowSubview: own_navigation_bar)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        request_data()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ignore_somebody, object: nil)
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func like_ignore_hanlde(noti:Notification){
            
    //         ["accid": self.accid,"likeOption":true]
        let json = JSON.init(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        let item = self.data_array.removeFirst(where: {$0.accid == accid})
            
        if item != nil{
            
            self.pause_video()
            
            self.collectionView.reloadData()
        }
    }

    
//    MARK: SetUp Data
    lazy var headerModel:ST_HotSupplementViewModel = {
      return ST_HotSupplementViewModel.init(title: "时下最火特质", imageUrl: "")
    }()
    
    lazy var param:[String:Int] = {
       return ["type":4]
    }()
    
    fileprivate func request_data(){
        
        JVrequest(PH.hotPeculiarityListApi,parameters:param, success: { (json) in
            
            print("最火特质的数据：",json["data"])
            
            let data = json["data"]
            
            self.headerModel.imageUrl = data["img"].stringValue
            
//            let list = data["list"].arrayValue
            
            if let list = [ST_PeculiaritySquarePersonChildModel].deserialize(from: data["list"].rawString() ?? "") as? [ST_PeculiaritySquarePersonChildModel]{
                
               let aArray = ST_ShowTraitCellModel.describe(modelArray: list)
                           
               self.data_array = aArray
                
//                self.loadMoreDataStyle(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
//
//                    self.request_data()
//                }
                
            }
            
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
    
    
    
    //    MARK:- Player View
  
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
//    MARK:- properties

    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
//        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("特质_icon_返回"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
//        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        control.addTarget(self, action: #selector(title_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
       
    
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
       let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = 15
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 10, bottom: BTSafeAreaBottom, right: 10)
        return controlLayout
    }()
    
    fileprivate let sectionheader_height = 175*(ScreenWidth/375.0)
   
    /**
     首页展示人的 collectionView
     */
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_ShowTraitCell.self)
        
//        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_HotSupplementView.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
//    MARK:- Collection  Data Source
    fileprivate lazy var data_array = [ST_ShowTraitCellModel]()
    
//    MARK:- Play Operation
    fileprivate var current_play_index_path:IndexPath?
    
    
    
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        
        if TopmostViewController() != self{
            return
        }
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_ShowTraitCell , let dataItem = data_array[safe:indexPath.item] else{return}
        
        
        
        if dataItem.type != .video{
            
            return
        }
            
        cell.contentView.addSubview(playerView)
        
        let rect = cell.picutreframe_in_content_view()
         
        playerView.frame = rect
        
        
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: dataItem.imageUrl, videoUrl: dataItem.videoUrl, width: dataItem.width, height: dataItem.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in collectionView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            if let cell = item as? ST_ShowTraitCell,cell.model.type == .video{
                
                if let playIdx = collectionView.indexPath(for: cell){

                 if let last = foundIndex,last.item < playIdx.item{
                     continue
                 }
                    
                let rectInScreen = collectionView.convert(cell.frame, to: nil)
                            
                let intersect = containerRect.intersection(rectInScreen)
                
                let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                //               小于 70% 换下一个哈
                if percent < 0.8{
                    continue
                }
                
               foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
//        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
//               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
                // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        print("cell视频---切换到另外一个Item:",foundIndex?.item ?? "🈚️")
        
        return foundIndex
    }
    
    
    
    
    
}



extension ST_HotWaterfallViewController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ShowTraitCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        self.present_detail(indexPath: indexPath)
        
        
    }
    /*
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat {
        
        return sectionheader_height
        
    }*/
    
    /*
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_HotSupplementView.self, for: indexPath)
        
        view.model = self.headerModel
        
        return view
    }*/
    
//    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        /*
        let y = scrollView.contentOffset.y
        
        let offSet = sectionheader_height - y
        
        if offSet < 0{
            
            own_navigation_bar.alpha = 1
            
        }else if offSet >= own_navigation_bar_show_coefficient{
            
            own_navigation_bar.alpha = 0
        }else{
            own_navigation_bar.alpha = 1-offSet/own_navigation_bar_show_coefficient
        }*/
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
                scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
            scrollviewdidEndScroll(scrollView)
        
    }
    
//    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}



//MARK: - Navigation Bar Event
extension ST_HotWaterfallViewController{
    
    @objc func title_click(){
        
    }
    
    @objc func left_click(){
        
        self.goback_previous_controller()
    }
}

//MARK: - 跳转详情
extension ST_HotWaterfallViewController{
    
    
    func present_detail(indexPath:IndexPath) {
        
        
        guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol else{
                return
            }
            
            let model = data_array[indexPath.row]

            //      当前正在播放 并且不是当前点击这个
            if current_play_index_path != indexPath{
                
                pause_video()
    //            1视频 2 图片
                if model.type == .video{

                    let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                    
                    playerView.setUp(data_array: [currModel])
                }else{
                    
                    let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)
                    
                    playerView.setUp(data_array: [currModel])
                    
                }
                
            }
            
            transition.operationView = self.playerView
            
            let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
            
            playerView.present_start_rect = rectInScreen
            playerView.present_start_idx = indexPath
            playerView.fromeController = self
         
            let item = model
        
        
        
        ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, remark: item.sign, firstPhotoSize: CGSize.init(width: item.width, height: item.height), transition: transition, presentRootController: self)
        
    }

}

extension ST_HotWaterfallViewController:ST_PairsTransitionProtocol{
    
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}




//MARK: -  Fantastic Update

class ST_FantasticWaterfallViewController: ST_HotWaterfallViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("最佳更新特质")
        
        self.headerModel.title = "最佳更新特质"
    }
    
    override var param: [String : Int]{
        get{
            return ["type":5]
        }set{
            super.param = newValue
        }
    }
    
    
}
